package lyttest.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {
    @Value("${spring.redis.Host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;


    @Value("${spring.redis.jedis.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.max-wait}")
    private long maxWaitMillis;

    @Value("${spring.redis.jedis.max-active}")
    private int maxActive;


    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        return poolConfig;
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig);
        factory.setHostName(host);
        factory.setPort(port);
         factory.setPassword(password);
        // factory.setTimeout(2000);
        return factory;
    }

    // 使用stringRedisTemplate，在使用 StringRedisTemplate 的时候，使用方法得到的结果都是String类型
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        // StringRedisTemplate 默认已经为键和值配置了 StringRedisSerializer，因此不需要额外设置
        return template;
    }
}